--
-- Author: shunguo.chen
-- Date: 2018-03-07 16:46:25
--
-- ChessModel

local ChessInfo = import(".ChessInfo")
local ChessSelect = import(".ChessSelect")

local fileName = string.getModeName(...)
local ClassRef = class(fileName, app.mvc.ModelBase)

function ClassRef:ctor(data)
	self.super.ctor(self, data)
end

function ClassRef:init()
	self._chessInfo = nil
end

function ClassRef:getChessInfo()
	-- test
	-- if true then
	-- 	local uid1 = UD.player.uid
	-- 	local uid2 = UD.player.uid + 1
	-- 	local avatarParams1 = UD:getAvatarParams()
	-- 	avatarParams1.mountID = 0
	-- 	local avatarParams2 = UD:getAvatarParams()
	-- 	avatarParams2.uid = uid2 * -1
	-- 	avatarParams2.mountID = 0
	-- 	avatarParams2.gender = 2

	-- 	local testData = {
	-- 		cells = {
	-- 			{pos=2,actionId=18000,uids={}},
	-- 			{pos=3,actionId=13102,uids={}}, 
	-- 			{pos=5,actionId=18001,uids={}},
	-- 			{pos=4,actionId=17001,uids={}}, 
	-- 		}, 
	-- 		self = {
	-- 			baseInfo = {uid=uid1, pos=3},
	-- 			normalDiceNum = 60,
	-- 			goldeDiceNUm = 60,
	-- 			totalRemainTime = 1000,
	-- 			roleIDs = {20101, 20102},
	-- 			buffIDs = {3010101, 3010102},
	-- 			gameBuffID = 9020021
	-- 		},
	-- 		selfUserInfo = avatarParams1,
	-- 		target = {
	-- 			baseInfo = {uid=uid2, pos=2},
	-- 			normalDiceNum = 60,
	-- 			goldeDiceNUm = 60,
	-- 			totalRemainTime = 1000,
	-- 			roleIDs = {20101, 20102},
	-- 			buffIDs = {3010101, 3010102},
	-- 			gameBuffID = 0
	-- 		},
	-- 		targetUserInfo = avatarParams2,
	-- 		roundID = 1,
	-- 		roundUID = uid1,
	-- 		status = "DICE",
	-- 		actionUID = uid1,
	-- 		remainTime = 60
	-- 	}

	-- 	self._chessInfo = ChessInfo.new(testData)
	-- end

	return self._chessInfo
end

function ClassRef:isChessMap()
	local mapId = MapManager:getMapId()
	return mapId == tonumber(S("starChessBattleMapId"))
end

----------------------------------------- receive ------------------------------------
function ClassRef:S2C_StarChessGameInfo(msg)
	-- dump(msg, "S2C_StarChessGameInfo")
	self._chessInfo = ChessInfo.new(msg)

	-- 战斗中肯定就是谜棋的战斗，有战斗关闭
	if self._chessInfo:isBattle() then
		app:sendMsg("ChessController", "closeView")
		app:sendMsg("ChessController", "refreshMap")
	else
		app:sendMsg("ChessController", "openView")
		app:sendMsg("ChessController", "refreshMap")
	end
end

-- 回合开始
function ClassRef:S2C_StarChessRoundStart(msg)
	-- dump(msg, "S2C_StarChessRoundStart")
	if not self._chessInfo then return end

	local curTime = app:getTime()

	self._chessInfo.roundID = msg.roundID
	self._chessInfo.roundUID = msg.roundUID
	self._chessInfo.remainTime = msg.roundRemainTime
	self._chessInfo.status = msg.needDice and "DICE" or "WAIT"
	self._chessInfo.actionUID = msg.roundUID
	self._chessInfo:setInitTime(curTime)
	local player = self._chessInfo:getPlayer(msg.roundUID)
	player.totalRemainTime = msg.totalRemainTime
	player:setInitTime(curTime)

	app:sendMsg("ChessController", "onRoundStart", self._chessInfo)
	app:sendMsg("ChessController", "onStatusUpdate")
end

-- roll点结果
function ClassRef:S2C_StarChessDiceResult(msg)
	-- dump(msg, "S2C_StarChessDiceResult")
	if not self._chessInfo then return end
	-- 等待播放骰子动画，客户端设置的非活跃状态
	self._chessInfo.status = "WAIT"
	self._chessInfo.actionUID = msg.uid

	app:sendMsg("ChessController", "onRollResult", msg)
	app:sendMsg("ChessController", "onStatusUpdate")
end

-- 玩家移动
function ClassRef:S2C_StarChessPlayerMove(msg)
	-- dump(msg, "S2C_StarChessPlayerMove")
	if not self._chessInfo then return end

	self._chessInfo.actionUID = msg.uid
	self._chessInfo.status = "MOVE"
	local player = self._chessInfo:getPlayer(msg.uid)
	player.pos = msg.reallyEndPos

	self._chessInfo:updateCell(msg.reallyEndPos, msg.uid)

	app:sendMsg("ChessController", "onPlayerMove", msg.startPos)
	app:sendMsg("ChessController", "onStatusUpdate")
end

-- 玩家抉择
function ClassRef:S2C_StarChessPlayerSelect(msg)
	-- dump(msg, "S2C_StarChessPlayerSelect", 10)
	if not self._chessInfo then return end

	self._chessInfo.actionUID = msg.uid
	self._chessInfo.remainTime = msg.remainTime
	self._chessInfo.status = "SELECT"
	self._chessInfo:setInitTime(app:getTime())

	local chessSelect = ChessSelect.new(msg.info)
	self._chessInfo:setChessSelect(chessSelect)

	app:sendMsg("ChessController", "onPlayerSelect", chessSelect)
	app:sendMsg("ChessController", "onStatusUpdate")
end

-- 事件触发，仅用于显示
function ClassRef:S2C_StarChessActionInfo(msg)
	-- dump(msg, "S2C_StarChessActionInfo")
	if not self._chessInfo then return end

	app:sendMsg("ChessController", "onPlayerAction", msg)
end

-- 玩家信息更新（自己局部更新）
function ClassRef:S2C_StarChessOperation(msg)
	-- dump(msg, "S2C_StarChessOperation", 10)
	if not self._chessInfo then return end

	local player = self._chessInfo.myPlayer
	local tp = msg.type
	local op = msg.op
	local value = msg.value
	local ids = msg.ids
	if tp == "NORMDICEDATA" or tp == "GOLDENDICEDATA" or tp == "REMAINTIMEDATA" then
		local key
		if tp == "NORMDICEDATA" then
			key = "normalDiceNum"
		elseif tp == "GOLDENDICEDATA" then
			key = "goldeDiceNUm"
		else
			key = "totalRemainTime"
		end
		if op == "ADD" then
			player[key] = player[key] + value
		elseif op == "DELETE" then
			player[key] = player[key] - value
		else
			player[key] = value
		end
	elseif tp == "ROLEDATA" or tp == "BUFFDATA" then
		local key
		if tp == "ROLEDATA" then
			key = "roleIDs"
		else
			key = "buffIDs"
		end

		if op == "UPDATE" then
			player[key] = ids
		else
			local oldIds = player[key]
			if op == "ADD" then
				for i,v in ipairs(ids) do
					oldIds[#oldIds + 1] = v
				end
			else
				local newIds = {}
				for _,old in ipairs(oldIds) do
					local found = false
					for _,new in ipairs(ids) do
						if old == new then
							found = true
							break
						end
					end
					if not found then
						newIds[#newIds + 1] = old
					end
				end
				player[key] = ids
			end
		end

		if tp == "ROLEDATA" then
			player:updateRoles()
		else
			player:updateSkills()
		end
	elseif tp == "GAMEBUFFDATA" then
		-- 游戏buff信息，数值型，只有update
		player.gameBuffID = value
	end

	app:sendMsg("ChessController", "onChessOp", msg)
end

-- 玩家信息更新（回合结束整体更新）
function ClassRef:S2C_StarChessPlayerUpdate(msg)
	-- dump(msg, "S2C_StarChessPlayerUpdate", 10)
	if not self._chessInfo then return end
	self._chessInfo:updatePlayers(msg.players)
end

-- 星空谜棋战斗结果
function ClassRef:S2C_BattleEnd(msg)
	if not self._chessInfo then return end
	if not self:isChessMap() then return end
	-- dump(msg, "S2C_BattleEnd")

	app:sendMsg("ChessController", "onChessBattleResult", msg)
end

-- 星空谜棋结果
function ClassRef:S2C_StarChessResult(msg)
	-- dump(msg, "S2C_StarChessResult")

	self._chessInfo = nil
	app:sendMsg("ChessController", "onChessResult", msg)
end

----------------------------------------- request ------------------------------------
-- 进入谜棋地图，请求开始谜棋
function ClassRef:reqStartChess()
	if not self:isChessMap() then return end
	-- print("reqStartChess")
	app.session:request("pb_starchess.C2S_StarChessFinishEnterGame",{},function(msg)
		-- dump(msg, "C2S_StarChessFinishEnterGame")
	end)
end

-- 从谜棋地图回到现实地图
function ClassRef:reqBackToMap()
	app.session:request("pb_map.C2S_BackToLastMap", {})
end

-- 退出星空谜棋
function ClassRef:reqEscape()
	app.session:request("pb_starchess.C2S_StarChessEscape",{},function(msg)
		-- dump(msg, "C2S_StarChessEscape")
		if msg.ok then
			app:sendMsg("ChessController", "closeView")
		else
			display.pushToast(msg.error)
		end
	end, nil, function(errMsg)
		-- dump(errMsg, "C2S_StarChessEscape errMsg")
		app:sendMsg("ChessController", "closeView")
	end)
end

-- roll点
function ClassRef:reqRoll(num)
	-- print("reqRoll", num)
	app.session:request("pb_starchess.C2S_StarChessDice",{num=num})
end

-- 行动结束
function ClassRef:reqActionOver(tp)
	if not self._chessInfo then return end
	-- print("reqActionOver", self._chessInfo.actionUID, self._chessInfo:isMyAction(), self._chessInfo:isRobotAction())
	if self._chessInfo:isMyAction() or self._chessInfo:isRobotAction() then
		-- print("C2S_StarChessActionOver", self._chessInfo.status, tp)
		app.session:request("pb_starchess.C2S_StarChessActionOver",{type=tp})
	end
end

-- 抉择
function ClassRef:reqSelect(id)
	-- print("reqSelect", id)
	app.session:request("pb_starchess.C2S_StarChessSelect",{id=id})
end

return ClassRef